package com.cndw.kungfu.model.pvp.campcross;

import java.util.List;

import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.DataStaticCenter;
import com.cndw.kungfu.model.activity.domain.CrossServer;
import com.cndw.kungfu.vo.EventNotice;

public class CampCrossCore {
	
	private static int endTime;
	
	public static synchronized void runBoss(){
		int currentTime = TimeProcesser.getUnixTime();
		int morningTime = TimeProcesser.getMorningTime();
		int startTime = morningTime + CampCrossConfig.startTime;
		endTime = startTime + CampCrossConfig.campLifeTime;

		if (endTime < currentTime) {
			startTime += 86400;
			endTime += 86400;
		}

		Context.getTimerServer().scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				try {
					endTime = TimeProcesser.getMorningTime() + CampCrossConfig.startTime + CampCrossConfig.campLifeTime;
					start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, startTime - currentTime, 86400);

		Context.getTimerServer().scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				try {
					stop();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, endTime - currentTime, 86400);
		
	}
	
	private static synchronized void start(){
		LogUtil.getMain().debug("camp cross  start ...");
		int maxArea = CrossServer.getMaxArea();
		for (int i = 1; i <= maxArea; i++) {
			final int area = i;
			Context.getTimerServer().execute(new Runnable() {
				
				@Override
				public void run() {
					CampCrossArea.getByArea(area).start();
					
				}
			});
			
		}
		LogUtil.getMain().debug("camp cross  start ..."+maxArea);
	}
	
	private static synchronized void stop(){
		LogUtil.getMain().debug("camp cross stop ...");
		int maxArea = CrossServer.getMaxArea();
		for (int i = 1; i <= maxArea; i++) {
			final int area = i;
			Context.getTimerServer().execute(new Runnable() {
				
				@Override
				public void run() {
					CampCrossArea.getByArea(area).stop();
					
				}
			});
		}
	}

	public static int getEndTime() {
		return endTime;
	}

	public static void prossReport(CampCrossReport report) {
		List<CampCrossLog> logs = report.getLogs();
		EventNotice notice = new EventNotice(ConstantsRadio.camp, ConstantsRadio.campRecordsCross);
		notice.comitData(logs);
		notice.put("topPlayers", report.getTop3());
		notice.broadcast(DataStaticCenter.getCampCrossIds());
	}

	
	
}
